package org.csu.mypetstore.controller;

import com.alipay.api.AlipayApiException;
import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.domain.User;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CartService cartService;

    @GetMapping("/viewOrderForm")
    public CommonResponse<Order> viewOrderForm(HttpSession session){
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        System.out.println(cart);
         for(CartItem c:cart){
                System.out.println(c.getItem().getItemId());
            }
        if (cart == null){
            cart = new ArrayList<>();
            session.setAttribute("cart",cart);
        }
        User account = (User)session.getAttribute("user");
        Order order = new Order();
        order.initOrder(account,cart);

        session.setAttribute("creditCardTypes",order.getCardType());
        session.setAttribute("order",order);
         return CommonResponse.createForSuccess(order);
    }

    @GetMapping("/getConfirmOrder")
    @ResponseBody
    public CommonResponse<Order>  getConfirmOrder(HttpSession session){
        Order order = (Order)session.getAttribute("order");
        return CommonResponse.createForSuccess(order);
    }
    @PostMapping("/confirmOrder")
    @ResponseBody
    public CommonResponse<Order> confirmOrder(HttpServletRequest request, HttpSession session){
        Order order =(Order) session.getAttribute("order");
        int orderId = orderService.inOrder(order);
        //PrintWriter out = response.getWriter();
        String shippingAddressRequired=request.getParameter("shippingAddressRequired");
        //没选修改地址
        if(shippingAddressRequired.equals("false")){
            String cardType = request.getParameter("cardType");
            String creditCard = request.getParameter("creditCard");
            String expiryDate = request.getParameter("expiryDate");
            order.setCardType(cardType);
            order.setCreditCard(creditCard);
            order.setExpiryDate(expiryDate);
            order.setOrderId(orderId);
            session.setAttribute("order",order);
            //out.print("Checked");
            return CommonResponse.createForSuccess(order);

        }else{
            String cardType = request.getParameter("cardType");
            String creditCard = request.getParameter("creditCard");
            String expiryDate = request.getParameter("expiryDate");
            User account = (User)session.getAttribute("user");

            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");
            String address1 = request.getParameter("address1");
            String address2 = request.getParameter("address2");
            String city = request.getParameter("city");
            String state = request.getParameter("state");
            String zip = request.getParameter("zip");
            String country = request.getParameter("country");
            // 修改订单消息
            order.setOrderId(orderId);
            order.setCardType(cardType);
            order.setCreditCard(creditCard);
            order.setExpiryDate(expiryDate);

            order.setShipToFirstName(firstName);
            order.setShipToLastName(lastName);
            order.setBillToFirstName(account.getFirstname());
            order.setBillToLastName(account.getLastname());

            order.setShipAddress1(address1);
            order.setShipAddress2(address2);
            order.setBillAddress1(account.getAddress1());
            order.setBillAddress2(account.getAddress2());


            order.setShipCity(city);
            order.setBillCity(account.getCity());


            order.setShipState(state);
            order.setBillState(account.getState());


            order.setShipZip(zip);
            order.setBillZip(account.getZip());


            order.setShipCountry(country);
            order.setBillCountry(account.getCountry());


            session.setAttribute("order",order);
            //out.print("No Checked");
            return CommonResponse.createForSuccess(order);
        }
        //out.flush();
        //out.close();
    }

    @PostMapping("/finalOrder")
    public CommonResponse<List> order(HttpServletRequest request) throws AlipayApiException {
         HttpSession session = request.getSession();
        Order order = (Order) session.getAttribute("order");
        User user = (User) session.getAttribute("user");
        String username = user.getUsername();

          List<CartItem> cartList = (List<CartItem>)session.getAttribute("cart");
        orderService.insertOrder(order);

        //String INSERT_BROWSELOGS = "INSERT INTO BROWSELOGS(userid, browsedhistory,browsetime,historytype) VALUES(?,?,?,?);";
            String historystr = new String();
            for (int i = 0; i < cartList.size(); i++) {
               cartService.removeCartItemByUsernameAndItemId(username,cartList.get(i).getItem().getItemId());
                orderService.insertNewOrder(username,cartList.get(i).getItem().getItemId(),cartList.get(i).getItem().getProductId(),cartList.get(i).getQuantity(),cartList.get(i).getTotal(),true,cartList.get(i).getItem().getAttribute1());
            }
            Calendar calendar = Calendar.getInstance();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        return  CommonResponse.createForSuccess(cartList);
    }
}
